<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * Serves HTTP API XML schemas. We don't expose them directly via the web
 * server because we need to merge in schemas from different places (modules
 * etc.) under the same URI space.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMAPISchemaController extends DMAbstractController {

	private static function tryToOutputSchemaAtPath($schema_name, $path) {
		$it = new RecursiveDirectoryIterator($path);
		foreach (new RecursiveIteratorIterator($it) as $filename) {
			if (strpos(realpath($filename), "/.") === false) {
				if ($schema_name == basename($filename)) {
					header("Content-Type: " . DMMediaType::getTypeForExtension(
							DMHTTPRequest::getCurrent()->getURI()->getExtension()));
					die(file_get_contents($filename));
				}
			}
		}
	}

	public function index($schema_name) {
		if (!$schema_name) {
			header("HTTP/1.1 404 Not Found");
			die;
		}
		// first, scan for built-in schemas
		self::tryToOutputSchemaAtPath($schema_name,
				dirname(__FILE__) . "/../../includes/schema");

		// not found, check modules
		$mm = DMModuleManager::getInstance();
		foreach ($mm->getEnabledModules() as $module) {
			if ($module instanceof DMBridgeRepresentationSchemaModule) {
				self::tryToOutputSchemaAtPath($schema_name,
						$module->getPathToSchemas());
			}
		}

		$response = new DMHTTPResponse();
		$rep = DMHTTPResponseFactory::getRepresentation();
		$rep->setMediaType(new DMMediaType("text", "plain"));
		$rep->setBody("Schema not found");
		$response->setStatusCode(404);
		$response->setRepresentation($rep);
		$response->send();
		die;
	}

}
